#! /bin/bash

# Note this script should be run in the project's top directory

# TO DO: print help string

BUILDROOT=$1
if [ -z "${BUILDROOT}" ]; then
        BUILDROOT="buildroot-2023.02"
fi

SRC_ROOT=`pwd`
BUILDROOT_SRC_ROOT=${SRC_ROOT}/external/${BUILDROOT}

git submodule init && git submodule update
if [ $? -ne 0 ]; then
    echo "ERROR: failed to update submodules"
    exit -1;
fi

if [ ! -d ${BUILDROOT_SRC_ROOT} ]; then
    echo "ERROR: ${BUILDROOT} source not found"
    exit -1
fi

cp ${SRC_ROOT}/configs/${BUILDROOT}.config ${BUILDROOT_SRC_ROOT}/.config

cd ${BUILDROOT_SRC_ROOT}
NRPROC=$(cat /proc/cpuinfo | grep processor | wc -l)
if [ ${NRPROC} -gt 2 ]; then
    NRPROC=`expr ${NRPROC} - 2`
fi
make -j${NRPROC}
cd ${SRC_ROOT}